package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.OnlyInfoBean;
import com.fancy.learncenter.bean.TokenDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.RSA;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class RegsiterActivity extends BaseActivity {
    @Bind(R.id.font_normal)
    TextView fontNormal;
    @Bind(R.id.tel_edit)
    EditText telEdit;
    @Bind(R.id.account_delete)
    ImageView accountDelete;
    @Bind(R.id.code_edit)
    EditText codeEdit;
    @Bind(R.id.code_bt)
    Button codeBt;
    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.password_delete)
    ImageView passwordDelete;
    @Bind(R.id.password_again_edit)
    EditText passwordAgainEdit;
    @Bind(R.id.password_again_delete)
    ImageView passwordAgainDelete;
    @Bind(R.id.temp)
    CardView temp;
    @Bind(R.id.agree_text)
    TextView agreeText;
    @Bind(R.id.register_agreement)
    TextView registerAgreement;
    @Bind(R.id.accepte)
    LinearLayout accepte;
    @Bind(R.id.regist_bt)
    Button registBt;
    @Bind(R.id.login_webview)
    WebView loginWebview;
    @Bind(R.id.activity_login)
    RelativeLayout activityLogin;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regsiter, Status.STATUS);
        ButterKnife.bind(this);

        getToken();

    }


    @OnClick({R.id.back_image, R.id.code_edit, R.id.account_delete, R.id.code_bt, R.id.password_delete, R.id.password_again_delete, R.id.agree_text, R.id.regist_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.code_edit:
                break;
            case R.id.back_image:
                finish();
                break;
            case R.id.code_bt:
                if (Utils.isMobileNO(telEdit.getText().toString())) {
                    autoLoop();
                } else {
                    ToastUtil.show("请输入正确的手机号");
                }
                break;
            case R.id.password_delete:
                passwordEdit.setText("");
                break;
            case R.id.password_again_delete:
                passwordAgainEdit.setText("");
                break;
            case R.id.account_delete:
                telEdit.setText("");
                break;
            case R.id.accepte:
                break;
            case R.id.regist_bt:

                if (Utils.isMobileNO(telEdit.getText().toString())) {

                    if (!TextUtils.isEmpty(codeEdit.getText().toString())) {
                        if (!TextUtils.isEmpty(passwordEdit.getText().toString()) && passwordEdit.getText().toString().equals(passwordAgainEdit.getText().toString())) {
                            putRegist();
                        } else {
                            ToastUtil.show("密码输入不一致");
                        }
                    } else {
                        ToastUtil.show("验证码不能为空");
                    }
                } else {
                    ToastUtil.show("请输入正确的手机号");
                }

                break;
        }
    }

    private void successfulUi() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }


    private void getToken() {
        HttpMehtod.getInstance().getToken(new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<TokenDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), TokenDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<TokenDataBean>() {
                    @Override
                    public void success(TokenDataBean dataBean) {
                        Constant.loginToken = dataBean.getLoginToken();
                        Constant.JSESSIONID = dataBean.getJSESSIONID();

                        LogUtil.MyLog("TokenDataBean", Constant.JSESSIONID + "======rsaStr==" + Constant.loginToken);
                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();

            }
        });
    }

    /**
     * 获取验证码
     */

    private void getCode() {
        HttpMehtod.getInstance().getRegsiterCode(telEdit.getText().toString(), new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<OnlyInfoBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), OnlyInfoBean.class);

                if (!TextUtils.isEmpty(baseBean.getInfo().getMessage())) {
                    ToastUtil.show(baseBean.getInfo().getMessage());
                    stopLoop();
                }
            }
        });
    }

    public void putRegist() {

        String rsaStr = "";
        try {
            rsaStr = RSA.ecrypt(Constant.loginToken + passwordEdit.getText().toString(), Constant.RSA_PUBLIC_KEY, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtil.MyLog("RSA", "======rsaStr==" + rsaStr);
        Map map = new HashMap();
        map.put("password", rsaStr);
        map.put("mobile", telEdit.getText().toString());
        map.put("vCode", codeEdit.getText().toString());
        HttpMehtod.getInstance().regist(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<OnlyInfoBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), OnlyInfoBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack() {

                    @Override
                    public void success(Object dataBean) {
                        successfulUi();
                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }
        });
    }

    private Subscription subscribe_auto;

    int currentTime = 60;

    private void autoLoop() {
        getCode();
        codeBt.setEnabled(false);
//        codeBt.setBackgroundColor(Color.parseColor("#01D7A7"));
        currentTime = 60;
        codeBt.setText("" + currentTime);
        if (subscribe_auto == null || subscribe_auto.isUnsubscribed()) {
            subscribe_auto = Observable.interval(1, 1, TimeUnit.SECONDS)
                    //延时3000 ，每间隔3000，时间单位
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            currentTime--;
                            codeBt.setText(currentTime + "");
                            if (currentTime <= 0) {
                                stopLoop();
                            }
                        }
                    });
        }
    }

    private void stopLoop() {
        codeBt.setEnabled(true);
        codeBt.setText("获取验证码");
//        codeBt.setBackgroundColor(Color.parseColor("#01D7A7"));
        if (subscribe_auto != null && !subscribe_auto.isUnsubscribed()) {
            subscribe_auto.unsubscribe();
        }
    }

}
